import os
from lxml import etree
from StringIO import StringIO
import cherrypy

# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 

# set the working directory
_apppath = os.path.realpath('.')

# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 

# XSLT Transformation
def transform(aXMLString,aXSLPath):
    xsltDoc = etree.parse(open(aXSLPath))
    transform = etree.XSLT(xsltDoc)
    doc = etree.parse(StringIO(aXMLString))
    return str(transform(doc))

# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 

# add a static directory to the config
def addStaticDir(conf,aDir):
     conf[aDir] = {'tools.staticdir.on': True, 'tools.staticdir.dir': _apppath + aDir}

# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

class kolsearch:
    # /-method
    def index(self,mode="KolSearch",q=""):
        # variables "mode" a "q" (the searchterm) are passed to the XSL as attributes
        xml = '<x mode=' + '"' + mode + '" q="' + q +'"/>'
        # start XSL transformation
        page = transform(xml,'KolSearch.xsl')      
        # return generated HTML
        return page
    
    # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    # searchcontroller
    def search(self, q, mode, sa):
        
        if mode == 'Web':
            # start a normal Google Websearch
            url = 'http://www.google.com/search?hl=en&q=' + q + '&btnG=Google+Search'
        elif mode == 'Wiki':
            # search TheKolWiki
            url = 'http://kol.coldfront.net/thekolwiki/index.php/Special:Search?search=' + q + '&go=go'
        elif mode == 'Forum':
            # search the Forums Of Loathing
            url = 'http://forums.kingdomofloathing.com/search.php?mode=results&search_keywords=' + q
        # redirect
        raise cherrypy.HTTPRedirect(url)
    
    # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    # only "exposed" methods will be available via url        
    index.exposed = True
    search.exposed = True
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 

# initialize configuration dictionary
conf={}

# add a static directory for the images
addStaticDir(conf,'/graphics')

# initialize the server
cherrypy.config.update({'server.socket_port'    : 8080})

# start the server with main class and config file
cherrypy.quickstart(kolsearch(), config=conf)